#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

void writer(int wfd)
{
	const char* str = "这是子进程";
	char buffer[128];
	int cnt = 0;
	pid_t pid = getpid();
	while(1)
	{
		snprintf(buffer,sizeof(buffer),"信息：%s,pid：%d,count：%d\n",str,pid,cnt);

		write(wfd,buffer,strlen(buffer));
		cnt++;
		sleep(1);
	}
}

void reader(int rfd)
{
	char buffer[1024];
	while(1)
	{
		ssize_t n = read(rfd,buffer,sizeof(buffer)-1);
		(void)n;
		printf("父进程收到消息：%s",buffer);
	}
}

int main()
{
	//1、创建管道
	int pipefd[2];
	int n = pipe(pipefd);
	if(n < 0)	return 1;

	printf("pipefd[0]: %d,pipefd[1]: %d\n",pipefd[0],pipefd[1]);//fd应该为3、4,0下标为read，1下标为write

	//2、进程间通信
	pid_t id = fork();
	if(id == 0)
	{
		//child: w
		close(pipefd[0]);//关闭r文件

		writer(pipefd[1]);

		exit(0);
	}

	//father r
	close(pipefd[1]);//关闭w文件
	
	reader(pipefd[0]);
	wait(NULL);
	return 0;
}
